<!-- eslint-disable @typescript-eslint/ban-ts-comment -->
<script setup lang="ts">
import { ref } from 'vue'
import Map from '@arcgis/core/Map.js'
import MapView from '@arcgis/core/views/MapView.js'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer.js'
import dayjs from 'dayjs'
import Point from '@arcgis/core/geometry/Point'
import { signActivity } from '@/api/volunteer'
import { SignInActivityRequest } from '@/types/volunteer'
import { GetIndividualVolunteerActivities } from '@/api/volunteer'
import { GetIndividualVolunteerActivitiesResponse } from '@/types/volunteer'
import { onMounted } from 'vue'
import { AnnotationLayer, SpaceLayer } from '@/utils/TianDiTuExtension'
import { IonPage, IonButton, alertController } from '@ionic/vue'
import { Geolocation } from '@capacitor/geolocation'
import * as geometryEngine from '@arcgis/core/geometry/geometryEngine'

// 创建一个用于显示 alert 的函数
async function showAlert(message: string) {
  const alert = await alertController.create({
    header: '提示',
    message: message,
    buttons: ['确认']
  })
  await alert.present()
}

//初始化地图容器
const mapViewContainer = ref<HTMLDivElement>()

//添加要素图层
const voluntaryLayer = new FeatureLayer({
  url: 'https://services8.arcgis.com/CmXfu09loK81if9H/arcgis/rest/services/VoluntaryActivityLayer/FeatureServer/1',
  outFields: ['*']
})

//初始化地图
const map = new Map({
  // basemap styles service
  basemap: {
    baseLayers: [SpaceLayer, AnnotationLayer]
  },
  layers: [voluntaryLayer]
})

//初始化mapview
const view = new MapView({
  map: map,
  center: [116.7963581069489, 36.53729500053177], // Longitude, latitude
  zoom: 13 // Zoom level
})

//待dom元素完成后加入
onMounted(async () => {
  view.container = mapViewContainer.value!
  view.ui.add('signInButton', 'top-right')
})

//签到按钮点击事件
const SignIn = async () => {
  // TODO: 签到逻辑

  // 获取当前用户可签到的活动
  const activities = await GetIndividualVolunteerActivities()
  let nowActivity: GetIndividualVolunteerActivitiesResponse | null = null

  const now = dayjs() // 获取当前时间

  activities.data.forEach((activity) => {
    // 判断是否在活动时间内
    if (dayjs(activity.activityStartTime).isBefore(now) && dayjs(activity.activityEndTime).isAfter(now)) {
      nowActivity = activity
    }
  })

  // 如果当前无可签到的活动，则提示
  if (!nowActivity) {
    showAlert('当前无可签到的活动')
    return
  }

  // 获取当前用户位置
  try {
    const position = await Geolocation.getCurrentPosition()
    const { latitude, longitude } = position.coords
    const userLocation = new Point({
      longitude: longitude,
      latitude: latitude
    })

    // TODO: 在这里添加检查用户是否在活动区域内的逻辑,如果在活动区域内，则签到
    const query = voluntaryLayer.createQuery()
    query.geometry = userLocation
    query.spatialRelationship = 'intersects'
    query.outFields = ['*'] // 或者只包含你需要的字段
    const result = await voluntaryLayer.queryFeatures(query)
    if (result.features.length > 0) {
      for (const feature of result.features) {
        // 检查用户是否在这个面要素内
        const isInside = geometryEngine.contains(feature.geometry, userLocation)
        if (isInside) {
          //@ts-ignore
          await signActivity(new SignInActivityRequest(nowActivity.activityId))
          showAlert('签到成功')
        }
      }
    } else {
      showAlert('你不在活动区域内，无法签到')
    }
  } catch (error) {
    showAlert('获取位置或签到失败，请重试')
  }
}
</script>

<template>
  <ion-page>
    <div id="mapViewContainer" ref="mapViewContainer" class="mapView"></div>
    <ion-button @click="SignIn" id="signInButton">签到</ion-button>
  </ion-page>
</template>

<style scoped>
.mapView {
  width: 100%;
  height: 100%;
}
</style>
